import util from './tools'
import sha256 from './crypto-js/sha256';
import {
  Config
} from '../framework'

const headers = {
  // 设备号
  'X-CLIENT-ID': function () {
    return util.getClientID()
  },
  // 客户端类型区分 [h5 mini userAndroidApp userIosApp shopAndroidApp shopIosApp]
  'X-CLIENT-APPID': function () {
    return 'h5'
  },

  'X-CLIENT-TICKET': function () {
    return ''
  },
  // APP版本号
  'X-CLIENT-VERSION': function () {
    return 'v1.0.0'
  },
  // 手机系统平台
  'X-CLIENT-PLATFORM': function () {
    return 'android'
  },
  // 13位时间戳
  'X-CLIENT-TIME': function () {
    const now = new Date()
    return now.getTime()
  },

  'X-CLIENT-PAGE': function () {
    return location.href
  },
  // 32位随机数
  'X-CLIENT-NONCE': function () {
    return util.newUUID(true)
  }
}

/**
 * map升序排序 拼接secret
 * @param {*} params
 * @param {*} secret
 * @returns
 */
function sortMapJoin(params = {}, secret) {
  // 对象的value值做升序
  let arr = Object.values(params).sort();
  let keyArr = Object.keys(params)
  // TODO优化
  let tempArr = arr.map(item => {
    let currentKey = ''
    keyArr.forEach(key => {
      if (params[key] == item) {
        currentKey = key;
        return
      }
    })
    // 数组里面拼接 key+val
    return currentKey + item
  })
  tempArr.push(secret)
  let destStr = tempArr.join("&");
  // console.log(secret,tempArr,destStr);
  return String(destStr)
}

// 签名的算法
const getSign = function (header) {
  let parms = {};
  parms['nonce'] = String(header['X-CLIENT-NONCE']);
  parms['timestamps'] = String(header['X-CLIENT-TIME']).split("").reverse().join("");
  parms['cookie'] = Config.cookie;
  let sourceUrl = sortMapJoin(parms, Config.secret);
  return sha256(sourceUrl).toString()
}

export default {
  getHeaders() {
    let header = {}
    Object.keys(headers).forEach(key => {
      header[key] = headers[key].apply(this)
    })
    // console.log(getSign(header));
    header['X-CLIENT-SIGN'] = getSign(header);
    return header
  }
}

